package org.duiduo.server.utils;

import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * FastDFS工具类
 *
 * @author liangze
 * @date 2021/11/15 17:26
 */
public class FastDFSUtils {

    private static Logger LOGGER = LoggerFactory.getLogger(FastDFSUtils.class);

    /**
     * 初始化客户端
     * ClientGlobal.init: 读取配置文件，并初始化对应的属性
     */
    static {
        try {
            String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
            ClientGlobal.init(filePath);
        } catch (Exception e) {
            LOGGER.error("初始化FastDFS失败==>{}", e.getMessage());
        }
    }

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    public static String[] upload(MultipartFile file) {
        String name = file.getOriginalFilename();
        LOGGER.info("文件名:" + name);
        StorageClient storageClient = null;
        String[] uploadResults = null;
        try {
            // 获取storage客户端
            storageClient = getStorageClient();
            uploadResults = storageClient.upload_file(file.getBytes(), name.substring(name.lastIndexOf(".") + 1), null);
        } catch (Exception e) {
            LOGGER.error("上传文件失败==>{}", e.getMessage());
        }
        if (null == uploadResults) {
            LOGGER.error("上传失败, 状态码:{}", storageClient.getErrorCode());
        }
        return uploadResults;
    }

    /**
     * 获取文件信息
     *
     * @param groupName
     * @param remoteFileName
     * @return
     */
    public static FileInfo getFileInfo(String groupName, String remoteFileName) {
        StorageClient storageClient = null;
        try {
            // 获取storage客户端
            storageClient = getStorageClient();
            FileInfo fileInfo = storageClient.get_file_info(groupName, remoteFileName);
            return fileInfo;
        } catch (Exception e) {
            LOGGER.error("获取文件信息失败==>{}", e.getMessage());
        }
        return null;
    }

    /**
     * 文件下载
     *
     * @param groupName
     * @param remoteFileName
     * @return
     */
    public static InputStream downFile(String groupName, String remoteFileName) {
        StorageClient storageClient = null;
        try {
            // 获取storage客户端
            storageClient = getStorageClient();
            byte[] fileBytes = storageClient.download_file(groupName, remoteFileName);
            return new ByteArrayInputStream(fileBytes);
        } catch (Exception e) {
            LOGGER.error("文件下载失败==>{}", e.getMessage());
        }
        return null;
    }

    /**
     * 获取文件路径
     *
     * @return
     */
    public static String getTrackerUrl() {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = null;
        StorageServer storeStorage = null;
        try {
            trackerServer = trackerClient.getTrackerServer();
            storeStorage = trackerClient.getStoreStorage(trackerServer);
        } catch (Exception e) {
            LOGGER.error("获取文件路径失败==>{}", e.getMessage());
        }
        return "http://" + storeStorage.getInetSocketAddress().getHostString() + ":80/";
    }

    /**
     * 文件删除
     *
     * @param groupName
     * @param remoteFileName
     */
    public static void deleteFile(String groupName, String remoteFileName) {
        StorageClient storageClient = null;
        try {
            // 获取storage客户端
            storageClient = getStorageClient();
            storageClient.delete_file(groupName, remoteFileName);
        } catch (Exception e) {
            LOGGER.error("文件删除失败==>{}", e.getMessage());
        }
    }

    /**
     * 生成tracker服务器
     *
     * @return
     * @throws IOException
     */
    private static TrackerServer getTrackerServer() throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        return trackerClient.getTrackerServer();
    }

    /**
     * 生成storage客户端
     *
     * @return
     * @throws IOException
     */
    private static StorageClient getStorageClient() throws IOException {
        TrackerServer trackerServer = getTrackerServer();
        return new StorageClient(trackerServer);
    }

    /**
     * 测试
     *
     * @param args
     */
    public static void main(String[] args) {
        String phonePath = "F:\\Photo & Video\\Photo\\sheding Photo\\QQ图片20210930182105.jpg";
        StorageClient storageClient = null;
        String[] strings = null;
        try {
            String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
            ClientGlobal.init(filePath);
            storageClient = getStorageClient();
            strings = storageClient.upload_file(phonePath, null, null);
        } catch (Exception e) {
            LOGGER.error("失败==>{}", e.getMessage());
        }
        for (String string : strings) {
            System.out.println(string);
        }
    }
}
